<?php

namespace app\payment\admin;

use app\user\model\User as UserModel;

/**
 * 谷歌身份验证控制器
 */
class GoogleVerify extends Index
{

    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * 两步验证页面
     */
    public function verification($secret = null)
    {
        $info = UserModel::where(['id' => session('user_auth.uid')])->find();
        if (input('get_secret') == 1) {
            $GoogleVerification = new \GoogleAuthenticator\Verification();
            if (empty($secret)) {
                $secret = $GoogleVerification->generateSecret();
            }
            $url = $GoogleVerification->getUrl($info['username'], $info['merchant_id'], $secret);
            return json([
                'secret' => $secret,
                'QRCode' => $url,
            ]);
        }
        if ($this->request->isPost()) {
            $code = input('post.code/d', 0);
            $GoogleVerification = new \GoogleAuthenticator\Verification();
            $secret = $info['google_secret'];
            if ($GoogleVerification->checkCode($code, $secret)) {
                session('google_secret_status', 1);  // 标记为已验证
                $this->success('登录成功', url('admin/index/index'));
            } else {
                $this->error('验证失败');
            }
        }
        return $this->fetch();
    }
}
